package com.dfbz.controller.user;

import com.dfbz.common.Constr;
import com.dfbz.controller.BaseController;
import com.dfbz.model.*;
import com.dfbz.service.DeptService;
import com.dfbz.service.impl.DeptServiceImpl;
import com.dfbz.service.UserService;
import com.dfbz.service.impl.UserServiceImpl;
import com.dfbz.utils.PageUtil;
import com.dfbz.utils.StrUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

@WebServlet("/user/*")
public class UserController extends BaseController {

    private UserService userService = new UserServiceImpl();
    private DeptService deptService = new DeptServiceImpl();

    //个人中心详细信息
    public void look(HttpServletRequest req, HttpServletResponse resp){
        String userId = req.getParameter("userId");
        if (null!= userId && !"".equals(userId)) {

            req.setAttribute("userInfo", userService.getUserInfo(userId));
            req.setAttribute("deptList", deptService.getAll());
            try {
                req.getRequestDispatcher("/assets/html/user_look.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }else {
            String requestURI = req.getRequestURI();
            try {
                resp.sendRedirect(req.getContextPath()+requestURI);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //保存个人中心信息
    public void saveInfo(HttpServletRequest req, HttpServletResponse resp){
        String userIdStr = req.getParameter("userId");
        int userId = Integer.parseInt(userIdStr);
        String realName = req.getParameter("realName");
        String selectDept = req.getParameter("selectDept");
        String phone = req.getParameter("phone");
        String ageStr = req.getParameter("age");
        int age = Integer.parseInt(ageStr);
        String gender = req.getParameter("gender");
        String isSecret = req.getParameter("isSecret");
        if (isSecret!=null){
            isSecret="1";
        }else {
            isSecret="0";
        }

        UserInfo userInfo = new UserInfo(userId,realName,age,phone,gender);

        try {
            boolean baseInfo = userService.saveUserBaseInfo(userIdStr,isSecret);
            boolean detailInfo = userService.saveUserDetailInfo(userInfo);
            if (baseInfo){
                if (detailInfo) {
                    req.getRequestDispatcher("/user/look?userId=" + userId).forward(req, resp);
                }else {
                    req.getRequestDispatcher("/user/look?userId=" + userId).forward(req, resp);
                }
            }else {
                req.getRequestDispatcher("/user/look?userId=" + userId).forward(req, resp);
            }
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }

    }

    //用户列表
    public void getUsers(HttpServletRequest req, HttpServletResponse resp){
        String page = req.getParameter("page");
        String searchName = req.getParameter("userSearchName");

        Map userBaseInfo = (Map) req.getSession().getAttribute("userBaseInfo");
        if (null==userBaseInfo){
            try {
                req.getRequestDispatcher(req.getContextPath()+"/user/getUsers").forward(req,resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
            return;
        }

        int currentPage = 1;
        if (null!=page){
            currentPage=Integer.parseInt(page);
        }

        List<Map<String, Object>> userList = userService.findUserList(userBaseInfo.get("user_id").toString(),currentPage, searchName);

        req.setAttribute("userList",userList);
        long totalCount = userService.getUserTotal(searchName);
        long totalPage = PageUtil.getTotalPage(totalCount);
        long startPage = PageUtil.getStartPage(currentPage);
        long endPage = PageUtil.getEndPage(currentPage,totalCount);
        req.setAttribute("currentPage",currentPage);
        req.setAttribute("searchName",searchName);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("totalPage",totalPage);
        req.setAttribute("startPage",startPage);
        req.setAttribute("endPage",endPage);
        req.setAttribute("pageCount",Constr.PAGE_COUNT);

        try {
            req.getRequestDispatcher(req.getContextPath()+"/assets/html/user.jsp").forward(req,resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    //用户列表查看用户详细信息
    public void getUserInfo(HttpServletRequest req, HttpServletResponse resp){
        String userId = req.getParameter("userId");
        try {
            if (null!=userId) {
                Map<String, Object> map = userService.getUserInfo(userId);
                req.getSession().setAttribute("lookUserInfo", map);

                if ("0".equals(map.get("is_secret").toString())) {
                    req.getRequestDispatcher(req.getContextPath() + "/user/userInfo?userId=" + userId).forward(req, resp);
                } else {
                    req.getSession().setAttribute("secretMsg", "你没有权限查看该用户信息！");
                    resp.sendRedirect(req.getContextPath() + "/user/getUsers");
                }
            }else {
                resp.sendRedirect(req.getContextPath()+"/assets/html/home.jsp");
            }
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    //关注用户
    public void followUser(HttpServletRequest req, HttpServletResponse resp){
        PrintWriter pw = null;
        String ufId = req.getParameter("ufid");
        String checked = req.getParameter("focus");
        String userId = getUserId(req);
        try {
            pw = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (null!=pw) {
            if ("true".equalsIgnoreCase(checked)) {
                if (userId.equals(ufId)) {
                    pw.write("不能关注自己");
                } else {
                    UserFocus userFocus = userService.getAttentionUser(userId, ufId);
                    if (null!=userFocus) {
                        pw.write("不能重复关注");
                    } else {
                        boolean focus = userService.attentionUser(userId, ufId);
                        if (focus) {
                            pw.write("关注成功");
                        } else {
                            pw.write("关注失败");
                        }
                    }
                }
            } else {
                UserFocus attentionUser = userService.getAttentionUser(userId, ufId);
                Integer attentionUserId = attentionUser.getId();
                boolean unAttention = userService.unAttentionUser(attentionUserId);
                if (unAttention){
                    pw.write("取关成功");
                }else {
                    pw.write("操作频繁，请稍候再试！");
                }
            }
        }else {
            try {
                resp.sendRedirect(req.getContextPath()+"/user/getUsers");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //取消关注
    public void unfollowUser(HttpServletRequest req, HttpServletResponse resp){
        try {
            String data;
            //关注的id
            String ufId = req.getParameter("ufId");
            //当前登录id
            String userId = getUserId(req);
            UserFocus focus=userService.getFollowUser(userId,ufId);
            if (null!=focus){
                boolean b = userService.unFollowUser(focus.getId());
                if (b){
                    data="1";
                }else {
                    data="取消关注失败";
                }
            }else {
                data="操作频繁，请稍候再试";
            }
            resp.getWriter().write(data);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //更换头像
    public void uploadFile(HttpServletRequest req, HttpServletResponse resp){
        try {
            String fileName=StrUtil.getUUID() +Constr.IMG_SUFFIX;//用UUID生成唯一的编号
            InputStream is=null;
            FileOutputStream fos=null;
            try {
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                List<FileItem> items = upload.parseRequest(req);
                if (!items.isEmpty()){
                    FileItem file = items.get(0);
                    String name = file.getName();
                    if (!name.contains("jpg")){
                        resp.getWriter().write(req.getContextPath()+Constr.DEFAULT_PATH);
                        return;
                    }
                    is = file.getInputStream();
                    fos = new FileOutputStream(Constr.FILE_PATH+fileName);
                    byte[] bytes = new byte[4 * 1024];
                    int len;
                    while (-1!=(len=is.read(bytes))){
                        fos.write(bytes,0,len);
                    }
                }
            } catch (FileUploadException | IOException e) {
                e.printStackTrace();
            }finally {
                if (null!=fos){
                    fos.close();
                }
                if (null!=is){
                    is.close();
                }
            }
            //更新路径到数据库 还要更新会话作用域的数据
            String userId = getUserId(req);
            userService.uploadImg(userId,Constr.IN_PATH+fileName);
            Map<String, Object> map = userService.findUserBaseInfo(getUserName(req));
            req.getSession().setAttribute("userBaseInfo", map);
            resp.getWriter().write(Constr.IN_PATH+fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //关注用户列表
    public void getFocusUsers(HttpServletRequest req, HttpServletResponse resp){
        String page = req.getParameter("page");

        Map userBaseInfo = (Map) req.getSession().getAttribute("userBaseInfo");
        if (null==userBaseInfo){
            try {
                req.getRequestDispatcher(req.getContextPath()+"/user/getFocusUsers").forward(req,resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
            return;
        }

        int currentPage = 1;
        if (null!=page){
            currentPage=Integer.parseInt(page);
        }

        List<Map<String,Object>> userFocusList = userService.findUserFocusList(userBaseInfo.get("user_id").toString(),currentPage);
        req.setAttribute("userFocusList",userFocusList);
        long totalCount = userService.getUserFocusTotal(userBaseInfo.get("user_id").toString());
        long totalPage = PageUtil.getTotalPage(totalCount);
        long startPage = PageUtil.getStartPage(currentPage);
        long endPage = PageUtil.getEndPage(currentPage,totalCount);
        req.setAttribute("currentPage",currentPage);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("totalPage",totalPage);
        req.setAttribute("startPage",startPage);
        req.setAttribute("endPage",endPage);
        req.setAttribute("pageCount",Constr.PAGE_COUNT);

        try {
            req.getRequestDispatcher(req.getContextPath()+"/assets/html/my_user.jsp").forward(req,resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    //关注用户列表取关操作
    public void unAttentionUser(HttpServletRequest req, HttpServletResponse resp){
        PrintWriter pw = null;
        String focusId = req.getParameter("focusId");
        String userId = getUserId(req);
        try {
            pw = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean unAttention = userService.unAttentionUser(Integer.parseInt(focusId));
        if (null!=pw) {
            if (unAttention) {
                pw.write("取关成功");
            } else {
                pw.write("操作频繁，请稍候再试！");
            }
        }
    }

    //查看所关注的用户的信息
    public void focusLookUser(HttpServletRequest req, HttpServletResponse resp){
        String userId = req.getParameter("userId");
        try {
            if (null!=userId) {
                Map<String, Object> map = userService.getUserInfo(userId);
                req.getSession().setAttribute("lookUserInfo", map);
                if ("0".equals(map.get("is_secret").toString())) {
                    req.getRequestDispatcher(req.getContextPath() + "/user/userInfo?userId=" + userId).forward(req, resp);
                } else {
                    req.getSession().setAttribute("secretMsg", "你没有权限查看该用户信息！");
                    resp.sendRedirect(req.getContextPath() + "/user/getFocusUsers");
                }
            }else {
                resp.sendRedirect(req.getContextPath()+"/assets/html/home.jsp");
            }
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    //查看文章列表
    public void getArticles(HttpServletRequest req, HttpServletResponse resp){
        String page = req.getParameter("page");
        String searchName = req.getParameter("articleSearchName");
        Map userBaseInfo = (Map) req.getSession().getAttribute("userBaseInfo");
        if (null==userBaseInfo){
            try {
                req.getRequestDispatcher(req.getContextPath()+"/user/getArticles").forward(req,resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
            return;
        }

        int currentPage = 1;
        if (null!=page){
            currentPage=Integer.parseInt(page);
        }

        List<Map<String,Object>> articleList = userService.findArticleList(currentPage,searchName);
        req.setAttribute("articleList",articleList);
        long totalCount = userService.getArticleTotal(searchName);
        long totalPage = PageUtil.getTotalPage(totalCount);
        long startPage = PageUtil.getStartPage(currentPage);
        long endPage = PageUtil.getEndPage(currentPage,totalCount);
        req.setAttribute("currentPage",currentPage);
        req.setAttribute("searchName",searchName);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("totalPage",totalPage);
        req.setAttribute("startPage",startPage);
        req.setAttribute("endPage",endPage);
        req.setAttribute("pageCount",Constr.PAGE_COUNT);

        try {
            req.getRequestDispatcher(req.getContextPath()+"/assets/html/article.jsp").forward(req,resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    //查看文章信息
    public void lookArticle(HttpServletRequest req, HttpServletResponse resp){
        String articleId = req.getParameter("articleId");
        Map<String, Object> map = userService.getArticleInfo(articleId);
        req.getSession().setAttribute("lookArticleInfo",map);
        String userId = getUserId(req);
        List<Map<String,Object>> list = userService.getArticleFocusUser(articleId);
        // 删除登录用户本身
        list.removeIf(next -> userId.equals(next.get("user_id").toString()));

        req.getSession().setAttribute("articleFocusUser",list);
        Integer count = (Integer) map.get("browse_count");
        count++;
        userService.updateArticles(articleId,count);
        boolean isFocus = userService.checkUserIsCollect(userId,articleId);
        req.getSession().setAttribute("collectMsg",isFocus);
        try {
            req.getRequestDispatcher(req.getContextPath()+"/assets/html/article_detail.jsp").forward(req,resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    //文章详情查看用户信息入口
    public void articleUserInfo(HttpServletRequest req, HttpServletResponse resp){
        String userId = req.getParameter("userId");
        String articleId = req.getParameter("articleId");
        Map<String, Object> map = userService.getUserInfo(userId);
        req.getSession().setAttribute("lookUserInfo",map);
        try {
            if ("0".equals(map.get("is_secret").toString())){
                req.getRequestDispatcher(req.getContextPath()+"/assets/html/user_detail.jsp").forward(req,resp);
            }else {
                req.getSession().setAttribute("secretMsg","你没有权限查看该用户信息！");
                resp.sendRedirect(req.getContextPath() + "/user/lookArticle?articleId="+articleId);
            }
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    //收藏文章列表
    public void articleCollect(HttpServletRequest req, HttpServletResponse resp){
        String page = req.getParameter("page");
        String searchName = req.getParameter("collectSearchName");
        Map userBaseInfo = (Map) req.getSession().getAttribute("userBaseInfo");
        String userId = getUserId(req);
        if (null==userBaseInfo){
            try {
                req.getRequestDispatcher(req.getContextPath()+"/user/articleCollect").forward(req,resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
            return;
        }

        int currentPage = 1;
        if (null!=page){
            currentPage=Integer.parseInt(page);
        }

        List<Map<String,Object>> collectArticleList = userService.findCollectArticleList(userId,currentPage,searchName);
        req.setAttribute("collectArticleList",collectArticleList);
        long totalCount = userService.getCollectArticleTotal(userId,searchName);
        long totalPage = PageUtil.getTotalPage(totalCount);
        long startPage = PageUtil.getStartPage(currentPage);
        long endPage = PageUtil.getEndPage(currentPage,totalCount);
        req.setAttribute("currentPage",currentPage);
        req.setAttribute("searchName",searchName);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("totalPage",totalPage);
        req.setAttribute("startPage",startPage);
        req.setAttribute("endPage",endPage);
        req.setAttribute("pageCount",Constr.PAGE_COUNT);

        try {
            req.getRequestDispatcher(req.getContextPath()+"/assets/html/article_collect.jsp").forward(req,resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    // 发布文章
    public void addArticle(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        String articleTitle = req.getParameter("articleTitle");
        String articleContent = req.getParameter("articleContent");
        try {
            if (articleTitle!=null&&articleContent!=null){
                String userId = getUserId(req);
                Map<String, Object> map = userService.getUserInfo(userId);
                Article article = new Article(articleTitle, articleContent,0, new Date(), map.get("real_name").toString(), Integer.parseInt(userId));
                boolean addArticle = userService.addArticle(article);
                if (addArticle){
                    resp.sendRedirect(req.getContextPath()+"/user/getArticles");
                }else {
                    session.setAttribute("addArticleMsg","服务器繁忙，请稍候再试！");
                    resp.sendRedirect(req.getContextPath() + "/assets/html/article_add.jsp");
                }
            }else {
                session.setAttribute("addArticleMsg","请填写完整的文章信息！");
                resp.sendRedirect(req.getContextPath() + "/assets/html/article_add.jsp");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 收藏文章
    public void collectArticle(HttpServletRequest req, HttpServletResponse resp){
        String articleId = req.getParameter("articleId");
        String userId = getUserId(req);
        PrintWriter pw = null;
        String data = "";
        try {
            pw = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (articleId!=null&& userId!=null) {
            Favorite favorite = userService.findCollectInfo(userId,articleId);
            if (favorite==null) {
                boolean addMsg = userService.addFavorite(new Favorite(Integer.parseInt(userId), Integer.parseInt(articleId)));
                if (addMsg) {
                    data = "1";
                } else {
                    data = "0";
                }
            }else {
                data = "r";
            }
        }else {
            data = "e";
        }
        pw.write(data);
    }

    // 取消收藏文章
    public void unCollectArticle(HttpServletRequest req, HttpServletResponse resp){
        String articleId = req.getParameter("articleId");
        String userId = getUserId(req);
        PrintWriter pw = null;
        String data = "";
        try {
            pw = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (articleId!=null&& userId!=null) {
            Favorite favorite = userService.findCollectInfo(userId,articleId);
            boolean deleteMsg = userService.unCollectArticle(favorite.getId());
            if (deleteMsg){
                data="s";
            }else {
                data = "f";
            }
        }else {
            data = "e";
        }
        pw.write(data);
    }

}
